

import React, { Component } from 'react';
import { Tabs, Button, Table, Divider, Modal, Form, Input, Icon, notification, Select, Drawer, Row, Col } from 'antd';
import '@/assets/css/settings';
import QRCode from 'qrcode.react'
import * as APIService from '../../axios/api';
import { withRouter } from "react-router-dom";
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const FormItem = Form.Item;
//弹出通知提醒框
function openNotification(type, message) {
	notification.open({
		type: type,
		message: message,
		duration: 2,
	});
};
class App extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataSource: [],
			pagination: {
				current: 1,   //当前页
				pageSize: 10,   //每一页的条数
			},
			loading: false,
			visible: false,
			modalData: '',//选中的数据
			handleType: 0,// 修改1
			options: [],
			visible_all: false,
			id: [],
			printBatchList: [],
			printRecond: [],
			children1: [],
			children2: [],
			children3: [],
			children1_disabled: false,
			children2_disabled: true,
			children3_disabled: true,
			str:''
		}
	}

	componentDidMount() {
		this.fetch('pageNum=1&pageSize=10')
	}

	//分页查询
	fetch = (str) => {
		this.setState({ loading: true });
		APIService.printBaseDepotManagements(str).then(data => {
			// console.log(data)
			const dataSource=data.data.data;
			const pagination = { ...this.state.pagination };
            pagination.total = data.data.total;
            // pagination.style = utils.pageStyle;
            pagination.showSizeChanger = false;
            pagination.showQuickJumper = false;
            pagination.showTotal = total => `共 ${total} 条数据`
		    this.setState({
						dataSource:dataSource,
						loading:false,
						pagination
					})
		})
		APIService.queryNextNode('').then(res => {
			const dataList = res.data.data;
			this.setState({
				children1: dataList,
			})
		})
	}

	//新增按钮取消
	handleCancel = e => {
		this.props.form.resetFields();
		this.setState({
			visible: false,
			visible_two: false,
			visible_all: false
		});
	};

	printAll = (data) => {
		//获取表格的点击行的值 赋给表单
		this.props.form.setFieldsValue({
			storageLocationCod_print: data.storageLocationCod,
		})
		this.setState({
			visible_all: true,
			modalData: data,
		})
	}

	showPrintModal = (data) => {
		//获取表格的点击行的值 赋给表单
		this.props.form.setFieldsValue({
			storageLocationCod_print: data.storageLocationCod,
		})
		this.setState({
			//visible_two: true,
			modalData: data,
		})
	}

	print = (data1, type) => {
		var style = `<style type="text/css" media="print">
        @page {
            margin:0;
            background-color: white;
        }
        </style>`;
      var ele = document.createElement('div');
      ele.innerHTML = style;
      document.getElementsByTagName('head')[0].appendChild(ele.firstElementChild);
		this.props.form.validateFields(['storageLocationCod_print', 'storageLocationName_print', 'id'], (err, values) => {
			if (!err) {
				const data = {}
				data.storageLocationCod = values.storageLocationCod_print
				data.storageLocationName = values.storageLocationName_print
				data.id = this.state.modalData.id
				const that = this;
				if (type===1) {
					APIService.printByQuery(this.state.str).then(data=>{
						// console.log(data.data.data.slice(0,3))
						this.setState({ printBatchList: data.data.data })
						return data.data.data;
					}).then(data=>{
						for (var i = 0; i < data.length; i++) {
							this.changeImg(i)
						}
					})
					.then(() => {
						var printInnerHTML = window.document.getElementById('billDetails_ln').innerHTML;
						window.document.body.innerHTML = printInnerHTML
						window.print();
						window.location.reload();
					})
					// that.handleCancel();
					// that.props.form.resetFields();
					// that.fetch('');
				} else {
					//单次打印
					let printBatchList = [data1.storageLocationCod];
					this.setState({ printBatchList });
					// console.log(printBatchList)
					new Promise(function (resolve) {
						resolve();
					}).then(() => {
						for (var i = 0; i < this.state.printBatchList.length; i++) {
							this.changeImg(i)
						}
					}).then(() => {
						var printInnerHTML = window.document.getElementById('billDetails_ln').innerHTML;
						window.document.body.innerHTML = printInnerHTML
						window.print();
						window.location.reload();
					})
				}

			} else {
				console.log(err);
			}
		});
	}

	canvasToImage = (canvas) => {
		var image = new Image();
		// 指定格式 PNG 图片后缀可自定义
		image.src = canvas.toDataURL("image/png");
		image.style = "height:115px;width:115px";
		return image;
	}
	changeImg = (i) => {
		var mycanvas = document.getElementsByTagName('canvas');
		// console.log(mycanvas[i])
		var img = this.canvasToImage(mycanvas[i]);
		var ewmImg = document.getElementById('ewm' + i);
		ewmImg.append(img);
		// console.log(ewmImg)
	}

	// 修改
	submitAdd = (e) => {
		this.props.form.validateFields(['storageLocationCod', 'supplierCode', 'materialName', 'minimumStockQuantity', 'safetyStock', 'theHighestInventory', 'boxNumber', 'purchaseOrderType', 'materialCode', 'id', 'storageLocationLong', 'storageLocationWide', 'storageLocationHigh', 'peakLoad'], (err, values) => {
			if (!err) {
				values = Object.assign({}, values, { storageLocationCod: this.state.modalData.storageLocationCod, boxNumber: this.state.modalData.boxNumber, purchaseOrderType: this.state.modalData.purchaseOrderType, id: this.state.modalData.id, storageLocationLong: this.state.modalData.storageLocationLong, storageLocationWide: this.state.modalData.storageLocationWide, storageLocationHigh: this.state.modalData.storageLocationHigh, peakLoad: this.state.modalData.peakLoad })

				const that = this;
				APIService.updateBaseFluentRack(values).then(data => {
					if (data.data.code === 200) {
						openNotification('success', '操作成功')
					} else {
						openNotification('warning', data.data.msg)
					}
					that.handleCancel();
					that.props.form.resetFields();
					that.setState({
						visible: false,
					});
					that.fetch('');
				})
			}
		}
		);
	}

	onExpand = (record, index, indent, expanded) => { }

	//  1修改
	showModal = (data, type) => {
		if (type === 1) {
			this.props.form.setFieldsValue({
				id: data.id,
				purchaseOrderType: data.purchaseOrderType,
				materialCode: data.materialCode,
				boxNumber: data.boxNumber,
				storageLocationName: data.storageLocationName,
				materialName: data.materialName,
				supplierCode: data.supplierCode,
				minimumStockQuantity: data.minimumStockQuantity,
				safetyStock: data.safetyStock,
				storageLocationCod: data.storageLocationCod,
				theHighestInventory: data.theHighestInventory,
				storageLocationLong: data.storageLocationLong,
				storageLocationWide: data.storageLocationWide,
				storageLocationHigh: data.storageLocationHigh,
				peakLoad: data.peakLoad
			})
		}

		this.setState({
			visible: true,
			modalData: data,
			handleType: type,
			id: data.id,
		});
	};

	//抽屉
	showDrawer = () => {
		this.setState({
			visible: true,
		});
	};
	onClose = () => {
		this.setState({
			visible: false,
		});
	};

	//查询
	handleSearch = (e) => {
		this.setState({loading:true})
		this.props.form.validateFields(['storageLocationCode', 'depotName', 'regionName', 'shelvesName'], (err, values) => {
			let str = '';
			for (let key in values) {
				if (values[key]) {
					if (key == 'storageLocationCode') {
						// data['storageLocationCod'] = values[key]
						str += `&storageLocationCod=${values[key]}`;
					} else {
						str += `&${key}=${values[key]}`;
					}
				}
			}
			this.setState({str,pagination: {
				current: 1, 
				pageSize: 10, 
			},})
			console.log(str)
			this.fetch(str)
		});
	};

	onChange = (value) => {
		console.log(value);
	}

	// 至少显示一个
	displayRender = (label) => {
		return label[label.length - 1];
	}

	handleChange = (value) => {
		// console.log(`Selected: ${value}`);
		APIService.queryNextNode('?param=' + value).then(res => {
			const dataList = res.data.data;
			// console.log(dataList)
			this.setState({
				children2: dataList,
				children2_disabled: false
			})
		})
	}
	handleChange3 = (value) => {
		// console.log(`Selected: ${value}`);
		// if (value !== '') {
		// 	this.setState({children2_disabled:true,children1_disabled:true});
		// }else {
		// 	this.setState({children2_disabled:false,children1_disabled:false})
		// }
	}
	handleChange2 = (value) => {
		// console.log(`Selected: ${value}`);
		// if (value !== '') {
		// 	this.setState({children1_disabled:true});
		// }else {
		// 	this.setState({children1_disabled:false})
		// }
		APIService.queryNextNode('?param=' + value).then(res => {
			const dataList = res.data.data;
			// console.log(dataList)
			this.setState({
				children3: dataList,
				children3_disabled: false
			})
		})
	}
	
	// 切换分页
	handleTableChange = pagination => {
		this.props.form.validateFields(['storageLocationCode', 'depotName', 'regionName', 'shelvesName'],(err, values) => {
			var str=this.state.str;
			 str+='&pageNum='+pagination.current+'&pageSize='+pagination.pageSize
			this.setState({ pagination: pagination }, () => {
				this.fetch(str);
			});
				
			
		});
		
	};
	render() {
		const { getFieldDecorator } = this.props.form;
		const formItemLayout_addMenu = {
			labelCol: {
				sm: { span: 8 }
			},
			wrapperCol: {
				sm: { span: 9 }
			}
		}

		const columns = [

			{
				title: '编码',
				dataIndex: 'storageLocationCod',
			},

			{
				title: '存放物料名称',
				dataIndex: 'materialName',
			},

			{
				title: '物料编码',
				dataIndex: 'materialCode',
			},

			{
				title: '采购订单类型',
				dataIndex: 'purchaseOrderType',
			},

			{
				title: '盒子数量',
				dataIndex: 'boxNumber',
			},

			{
				title: '供应商编码',
				dataIndex: 'supplierCode',
			},

			{
				title: '最低库存量',
				dataIndex: 'minimumStockQuantity',
			},

			{
				title: '安全库存量',
				dataIndex: 'safetyStock',
			},

			{
				title: '最高库存量',
				dataIndex: 'theHighestInventory',
			},

			{
				title: '长',
				dataIndex: 'storageLocationLong',
			},

			{
				title: '宽',
				dataIndex: 'storageLocationWide',
			},

			{
				title: '高',
				dataIndex: 'storageLocationHigh',
			},

			{
				title: '最多载重',
				dataIndex: 'peakLoad',
			},

			{
				title: '操作',
				width: '9%',
				render: (text, record) => {
					return <span>
						<a onClick={() => this.showModal(record, 1)}>修改</a>
						<Divider type="vertical" />
						<a onClick={() => this.print(record, 0)}>打印</a>
					</span>
				}
			}
		]


		var operations = <div className="mydiv" > <Button icon="printer" onClick={() => this.print(this.state.dataSource, 1)} type="primary" > 批量打印 </Button></div >

		return (
			<div className="shadow-radius">

				<Form className="search-form" style={{ paddingBottom: 0 }}>
					<Row gutter={32}>
						<Col span={5}>
							<FormItem label="储位编码">
								{getFieldDecorator('storageLocationCode')(
									<Input placeholder='储位编码' />
								)}
							</FormItem>
						</Col>
						<Col span={5}>
							<FormItem label="仓库选择">
								{getFieldDecorator('depotName',{initialValue: ''})(
									<Select
										placeholder="请选择"
										onChange={this.handleChange}
										style={{ width: '100%' }}
										disabled={this.state.children1_disabled}
									>
										<Option value=''>----------</Option>
										{this.state.children1.map((item, key) => {
											return <Option key={key} value={item}>{item}</Option>
										})}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col span={5}>
							<FormItem label="区域选择">
								{getFieldDecorator('regionName',{initialValue: ''})(
									<Select disabled={this.state.children2_disabled}
										placeholder="请选择"
										onChange={this.handleChange2}
										style={{ width: '100%' }}
									>
										<Option value=''>----------</Option>
										{this.state.children2.map((item, key) => {
											return <Option value={item} key={key}>{item}</Option>
										})}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col span={6}>
							<FormItem label="货架选择">
								{getFieldDecorator('shelvesName',{initialValue: ''})(
									<Select disabled={this.state.children3_disabled}
										// mode="tags"
										// size="normal"
										placeholder="请选择"
										onChange={this.handleChange3}
										style={{ width: '100%' }}
									>
										<Option value=''>----------</Option>
										{this.state.children3.map((item, key) => {
											return <Option value={item} key={key}>{item}</Option>
										})}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col span={2} style={{ marginRight: '10px', display: 'flex' }} className="serarch-btns">
							<FormItem>
								<Button icon="search" type="primary" htmlType="submit" className={'btn'} onClick={this.handleSearch}>
									查询
								</Button>
							</FormItem>
						</Col>
					</Row>
				</Form>

				<Tabs defaultActiveKey="1" tabBarExtraContent={operations}>
					<TabPane tab={<span><Icon type="table" /><strong>货架详情</strong> </span>} key="1" >
						<Table columns={columns} onChange={this.handleTableChange}  dataSource={this.state.dataSource} pagination={this.state.pagination} loading={this.state.loading} rowKey={record => record.storageLocationCod} size="small"/>
					</TabPane>
				</Tabs>

				<Drawer
					width='720px'
					title="修改"
					visible={this.state.visible}
					centered
					onOk={this.submitAdd}
					onCancel={this.handleCancel}
					onClose={this.onClose}
					bodyStyle={{ paddingBottom: 80 }}
				>
					<Form layout="vertical" hideRequiredMark>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="编码">
									{getFieldDecorator('storageLocationCod', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="存放物料名称">
									{getFieldDecorator('materialName', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="存放物料编码">
									{getFieldDecorator('materialCode', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="采购订单类型">
									{getFieldDecorator('purchaseOrderType', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="盒子数量">
									{getFieldDecorator('boxNumber', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="供应商编码">
									{getFieldDecorator('supplierCode', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="最低库存量">
									{getFieldDecorator('minimumStockQuantity', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="安全库存量">
									{getFieldDecorator('safetyStock', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="最高库存量">
									{getFieldDecorator('theHighestInventory', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="长">
									{getFieldDecorator('storageLocationLong', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>

						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="宽">
									{getFieldDecorator('storageLocationWide', {})(<Input />)}
								</Form.Item>
							</Col>
							<Col span={12}>
								<Form.Item label="高">
									{getFieldDecorator('storageLocationHigh', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>
						<Row gutter={16}>
							<Col span={12}>
								<Form.Item label="最多载重">
									{getFieldDecorator('peakLoad', {})(<Input />)}
								</Form.Item>
							</Col>
						</Row>
					</Form>
					<div
						style={{
							position: 'absolute',
							right: 0,
							bottom: 0,
							width: '100%',
							borderTop: '1px solid #e9e9e9',
							padding: '10px 16px',
							background: '#fff',
							textAlign: 'right',
						}}
					>
						<Button onClick={this.onClose} style={{ marginRight: 8 }}>
							取消
            			</Button>
						<Button onClick={this.submitAdd} type="primary">
							保存
            			</Button>
					</div>
				</Drawer>
				<div id={"billDetails_ln"} style={{ padding: 0, margin: 0 }}>
					{this.state.printBatchList.map((e, i) => {
					   if(e){
						let arr = e.split('')
						var  str = arr[0]+'-'+arr[1]+'-'+arr[2]+'-'+arr[3]+arr[4]+'-'+arr[5]+'-'+arr[6]+arr[7]
					}

						return <div className='cardStyle' id={'cardStyle' + i}   key={i} style={{width:'135px',textAlign:'center',marginTop:'8px',marginLeft:'4px'}}>
									<div style={{ fontSize: '18px', fontWeight: 700}}>{str}</div>
									<QRCode
										value={e}  //value参数为生成二维码的链接
										size={115} //二维码的宽高尺寸
										fgColor="#000000"  //二维码的颜色
										style={{ display: 'none' }} />
									<div className="codeImg" id={"ewm" + i} style={{marginTop:'3px'}}></div>
						</div>
					})}
				</div>

			</div>
		)
	}
}
export default Form.create()(withRouter(App));